<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      ref="treeRef"
      title="部门列表"
      toolbar
      search
      :clickRowToExpand="false"
      :treeData="treeData"
      :replaceFields="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, unref } from 'vue';

  import { BasicTree, TreeItem, TreeActionType } from '/@/components/Tree';
  import { getBranchList } from '/@/api/system/system';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeRef = ref<Nullable<TreeActionType>>(null);
      const treeData = ref<TreeItem[]>([]);

      function getTree() {
        const tree = unref(treeRef);
        if (!tree) {
          throw new Error('tree is null!');
        }
        return tree;
      }

      async function fetch() {
        treeData.value = (await getBranchList()) as unknown as TreeItem[];
      }

      function handleSelect(keys: string) {
        emit('select', keys[0]);
      }

      onMounted(async () => {
        await fetch();
        getTree().expandAll(true);
      });
      return { treeData, handleSelect, treeRef };
    },
  });
</script>
